# -*- coding = utf-8 -*-
#@Time: 2021/7/17 14:22
#@Author: 卜白
#@File: models.py
#@Software: PyCharm

# 用户apps的模板文件
from pymysql.err import IntegrityError
import settings
import datetime
from base_model import Base_Model
from flask import current_app
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadSignature, SignatureExpired

class User(Base_Model):
    # 用户注册
    def user_registered(self,username,password,phone,email):
        into_sql = 'insert into book_users (username,password,phone,email,create_time,update_time) values ("%s","%s","%s","%s","%s","%s");' % (username,password,phone,email,datetime.datetime.now(),datetime.datetime.now())
        try:
            self.cursor.execute(into_sql)  # 执行sql命令
            self.conn.commit()
        except IntegrityError as e:
            # 数据库操作错误后的回滚
            self.conn.rollback()
            # 表示手机号出现了重复值，即手机号已注册过
            current_app.logger.error(e)
            return 301
        except Exception as e:
            self.conn.rollback()
            # 注册失败
            current_app.logger.error(e)
            return 412
        else:
            return 200

    # 修改密码
    def change_password(self,newpsd,key,value):
        update_sql = 'update book_users set password = "{a}" where {b} = "{c}";'.format(a=newpsd,b=key,c=value)
        try:
            self.cursor.execute(update_sql)  # 执行sql命令
            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
            # 注册失败
            current_app.logger.error(e)
            return 412
        else:
            return 200

    # 查询手机号
    def get_user_mobile(self,mobile):
        sql = 'select phone from book_users where phone = "%s";' % mobile
        self.cursor.execute(sql)  # 执行sql命令
        
        return self.cursor.fetchone()

    # 根据用户名查询用户
    def get_user_all(self,username):
        sql = 'select id,username,password,phone from book_users where username = "{}"'.format(username)
        self.cursor.execute(sql)  # 执行sql命令

        return self.cursor.fetchone()

    # 根据手机号查询用户
    def get_user_info(self, mobil):
        sql = 'select id,username,password,phone from book_users where phone = "{}"'.format(mobil)
        self.cursor.execute(sql)  # 执行sql命令

        return self.cursor.fetchone()

    # 生成token
    def create_token(self,user_id,username):
        """
        生成token
        :param user_id: 用户id
        :return:
        """
        # 第一个参数是内部的私钥，这里写在配置信息里，如果只是测试可以写死
        # 第二个参数是有效期（秒）, expires_in=Config.TOKEN_EXPIRATION
        s = Serializer(settings.Config.SECRET_KEY)
        # 接收用户id转换与编码
        token = s.dumps({"id": user_id, "username": username}).decode('ascii')
        return token

    # 解析token
    def verify_auth_token(self,token):
        s = Serializer(settings.Config.SECRET_KEY)
        # token正确
        try:
            data = s.loads(token)
            return data
        # token过期
        except SignatureExpired as e:
            current_app.logger.error(e)
            return 405
        # token错误
        except BadSignature as e:
            current_app.logger.error(e)
            return 404
